package com.tacademy.jmtwitter;

import java.util.*;

import android.app.*;
import android.content.*;
import android.os.*;
import android.util.*;

public class NotificationService extends Service {
	public static final int ID_NOTI = 1;
	long mSinceId;
	int mCountNew;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d("Notification", "onStartCommand");
		sinceId();
		
		stopSelf();
		return  START_NOT_STICKY;

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d("Notification", "onDestroy");
	}

	void showNotification() {
		Log.d("Notification", "노티시작");
		Notification noti = new Notification(R.drawable.ic_launcher,
				"보시지 않은 메시지가 " + mCountNew + "개 있습니다.",
				System.currentTimeMillis());
		Intent intent = new Intent(this, JMTwitterActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				intent, 0);

		noti.setLatestEventInfo(this, "보지마세요 >_< 부그럽 잉잉", "보시지 않은 메시지가 " + mCountNew + "개 있습니다.", pendingIntent);
		// RemoteViews - noti.contentView

		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nm.notify(ID_NOTI, noti);
	}

	void hideNotification() {
		// 보통 액티비티의 onresume에서 처리
		Log.d("Notification", "하이드 노티");
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nm.cancel(ID_NOTI);
	}

	public void sinceId() {

		new Thread() {
			@Override
			public void run() {
				SharedPreferences pref = getSharedPreferences(Authorize.SAVE, MODE_PRIVATE);
				mSinceId = pref.getLong("sinceId", JMTwitterActivity.sinceId);
				Log.d("Notification", "hideNotification");
				
				
				Log.d("Notification", "run");
				ArrayList<Status> dataList = new ArrayList<Status>();
				dataList = new TwitterApi(
						pref.getString(Authorize.TOKEN, null), pref.getString(
								Authorize.SECRET, null)).getHomeTimeline(12, mSinceId,
						0);
				mCountNew = dataList.size();
				mSinceId = Long.parseLong(dataList.get(0).getId());
				Log.d("Notification", "mCount는요  "+ mCountNew );
				if (0 != mCountNew) {
					Log.d("Notification", "showNotification  " );
					hideNotification();
					showNotification();
				}
				
				SharedPreferences.Editor edit = pref.edit();
				edit.putLong("sinceId", mSinceId);
				edit.commit();
				Log.d("jmkkk", "아이디 저장!!");
			}
		}.start();

	}

}
